package com.hanson.common.util;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.hanson.Const;
import com.hanson.common.bean.WeiXinConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * 二维码生成工具类
 * create by liaohq
 */
@Component
@Slf4j
public class QrCodeUtil {
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Value("${oss.local}")
    private String isLocal;


    /**
     * 合伙人分享二维码
     *
     * @param client
     * @param pid
     * @return
     */
    public String createQrCode(String client, int pid) {
        String qrUrl = null;
        if (client.equalsIgnoreCase(Const.CLIENT_MINI)) {
            try {
                byte[] imagesBytes = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes("uid="+pid, "pages/tabbar/userCenter", 277, true, null, false);
                ByteArrayInputStream swapStream = new ByteArrayInputStream(imagesBytes);
                qrUrl = FileUploadUtil.upload(isLocal, String.format("mini_qrcode_%s.png", UUID.randomUUID().toString()), swapStream);
            } catch (WxErrorException e) {
                e.printStackTrace();
                log.error("创建小程序二维码失败", e);
            }
        } else {
            try {
                //开始生成二维码
                qrUrl = BusinessUtil.generateQRCodeImage(isLocal, String.format("%s#/pages/tabbar/userCenter?uid=%s", weiXinConfig.getDomian(), pid), 277, 275);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("创建H5二维码失败", e);
            }
        }
        return qrUrl;
    }
}
